<template>
  <div class="app-container">
    <el-form :inline="true" :model="queryParams" class="demo-form-inline">

      <el-form-item label="ID" prop="userId">
        <el-input v-model="queryParams.userId" placeholder="id" />
      </el-form-item>

      <el-form-item label="昵称" prop="nickName">
        <el-input v-model="queryParams.nickName" placeholder="昵称" />
      </el-form-item>
      <el-form-item label="金额" prop="amount">
        <el-input v-model="queryParams.amount" placeholder="金额" />
      </el-form-item>
      <el-form-item label="开始日期" prop="startTime">
        <el-date-picker v-model="queryParams.startTime" type="datetime" placeholder="选择开始日期"
          value-format="yyyy-MM-dd HH:mm:ss" />
      </el-form-item>
      <el-form-item label="结束日期" prop="endTime">
        <el-date-picker v-model="queryParams.endTime" type="datetime" placeholder="选择结束日期"
          value-format="yyyy-MM-dd HH:mm:ss" />
      </el-form-item>
      <el-form-item label="订单编号" prop="orderNo">
        <el-input v-model="queryParams.orderNo" placeholder="订单编号" />
      </el-form-item>
      <el-form-item label="提现账户" prop="address">
        <el-input v-model="queryParams.address" placeholder="提现账户" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择">
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="提现类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择">
          <el-option label="usdt" value="usdt" />
          <el-option label="支付宝" value="alipay" />
          <el-option label="银行卡" value="bank" />

        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button type="primary" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <p style="white-space: pre-wrap">{{ statisticsTxt }}</p>
    <el-button type="primary" @click="onCopy">一键复制</el-button>
    <el-button type="primary" @click="onCopyMerge">一键合并复制</el-button>
    <el-button type="primary" @click="onSuccess">一键通过</el-button>
    <el-button type="primary" @click="onReject">一键驳回</el-button>
    <el-table v-loading="listLoading" ref="table" :data="list" style="margin-top: 20px;" element-loading-text="Loading"
      border fit highlight-current-row>
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column align="center" label="序号" width="95">
        <template slot-scope="scope">
          <span :style="{ color: scope.row.color }">{{ scope.$index }}</span>
        </template>
      </el-table-column>

      <el-table-column label="用户" align="center">
        <template slot-scope="scope">
          <span :style="{ color: scope.row.color }">{{ scope.row.nickName }}（{{ scope.row.userId
          }}）</span>
        </template>
      </el-table-column>

      <el-table-column label="备注	" align="center" prop="remarks">
        <template slot-scope="scope">
          <span :style="{ color: scope.row.color }">{{ scope.row.remarks }}</span>
        </template>
      </el-table-column>

      <el-table-column label="订单编号" align="center">
        <template slot-scope="scope">
          <span :style="{ color: scope.row.color }">{{ scope.row.orderNo }}</span>
        </template>
      </el-table-column>
      <el-table-column label="提现金额" align="center">
        <template slot-scope="scope">
          <span :style="{ color: scope.row.color }">{{ scope.row.amount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="提现类型" align="center">
        <template slot-scope="scope">
          <span :style="{ color: scope.row.color }">{{ scope.row.type }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开户行" align="center">
        <template slot-scope="scope">
          <span :style="{ color: scope.row.color }">{{ scope.row.bankOfDeposit }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template slot-scope="scope">
          <span :style="{ color: scope.row.color }">{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>

      <el-table-column label="审核状态" align="center">
        <template slot-scope="scope">
          <span :style="{ color: scope.row.color }">{{ setStateTxt(scope.row.status) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.row)">审核</el-button>

        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination :current-page.sync="queryParams.pageNum" :page-sizes="[30, 60, 90, 120]"
        :page-size.sync="queryParams.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"
        @size-change="fetchData" @current-change="fetchData" />
    </div>
    <showInfo ref="showInfo" />
  </div>
</template>

<script>
import { withdrawalList, approvalBatch, statisticsByStatus } from '@/api/table'
import showInfo from './showInfo.vue'
export default {
  components: {
    showInfo
  },
  data() {
    return {
      list: null,
      listLoading: true,
      timer: null,
      total: 0,
      statisticsTxt: ``,

      typeOptions: [
        { label: '虚拟货币', value: 'usdt' },
        { label: '人民币', value: 'rmb' }
      ],
      statusOptions: [
        { label: '申请中', value: 'applying' },
        { label: '审核通过', value: 'approved' },
        { label: '审核驳回', value: 'reject' }

      ],
      queryParams: {
        'hash': '',
        'orderNo': '',
        'pageNum': 1,
        'pageSize': 30,
        'status': '',
        'type': '',
        'userId': '',
        type: "", 
        address:""
      }
    }
  },
  created() {
    this.fetchData()
    // this.getStatisticsByStatus()
    // this.timer = setInterval(() => {
    //   this.fetchData()
    // }, 10000)
  },
  destroyed() {
    console.log('销毁')
    clearInterval(this.timer)
  },
  methods: {
    async getStatisticsByStatus() {
      const res = await statisticsByStatus({ startTime: this.queryParams.startTime, endTime: this.queryParams.endTime });
      if (res.code === 200) {
        console.log(res.data);
        const str = `
          提现统计：\n
          通过总金额：${res.data.successTotalAmount} \n
          usdt ${res.data.successUsdtTotalAmount}，支付宝${res.data.successRmbTotalAmount}，银行卡${res.data.successTransferTotalAmount}\n
          驳回总金额： ${res.data.rejectTotalAmount}\n
          usdt ${res.data.rejectUsdtTotalAmount}，支付宝${res.data.rejectRmbTotalAmount}，银行卡${res.data.rejectTransferTotalAmount}\n
          审核中总金额： ${res.data.applyingTotalAmount}\n
          usdt ${res.data.applyingUsdtTotalAmount}，支付宝${res.data.applyingRmbTotalAmount}，银行卡${res.data.applyingTransferTotalAmount}\n
        
        `
        this.statisticsTxt = str;
      }
    },
    
    onCopy() {
      const data = this.$refs.table.selection
      if (data.length) {
        let str = `序号  金额  账号信息\n`
        data.map((item, index) => {
          str += `${index}   ${item.amount}   ${item.address} \n`
        })
        const textarea = document.createElement('textarea');
        textarea.value = str;
        document.body.appendChild(textarea);
        textarea.select();
        try {
          const successful = document.execCommand('copy');
          const msg = successful ? '成功' : '失败';
          console.log('复制文本 ' + msg);
        } catch (err) {
          console.error('无法复制文本: ', err);
        }

        document.body.removeChild(textarea);
      }
    },
    onCopyMerge() {
      const data = this.$refs.table.selection
      if (data.length) {
        const resultMap = new Map();
        data.forEach(item => {
          let addressStr = item.address.replace(/\s/g, '');
          if (resultMap.has(addressStr)) {
            const existingItem = resultMap.get(addressStr);
            existingItem.amount += item.amount;
          } else {
            resultMap.set(addressStr, { ...item });
          }
        });
        console.log(resultMap)
        const result = Array.from(resultMap.values());
        let str = `序号  金额  账号信息\n`
        result.map((item, index) => {
          str += `${index}   ${item.amount}   ${item.address} \n`
        })
        const textarea = document.createElement('textarea');
        textarea.value = str;
        document.body.appendChild(textarea);
        textarea.select();
        try {
          const successful = document.execCommand('copy');
          const msg = successful ? '成功' : '失败';
          console.log('复制文本 ' + msg);
        } catch (err) {
          console.error('无法复制文本: ', err);
        }
        document.body.removeChild(textarea);
      }
    },
    onSuccess() {
      const data = this.$refs.table.selection
      if (data.length) {
        this.$confirm('此操作将批量同意, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let ids = []
          data.map(item => {
            ids.push(item.id)
          })
          approvalBatch({ ids, "status": "approved" }).then(res => {
            this.fetchData()
            this.$message({
              type: 'success',
              message: '成功!'
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
      }
    },
   
    // 一键驳回
    onReject() {

      const list = this.$refs.multipleTable.selection
      if (list.length) {
        this.$confirm('此操作将驳回审核, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let ids = []
          list.map(item => {
            ids.push(item.id)
          })
          approvalBatch({ ids: ids, status: "reject" }).then(res => {
            this.$message({
              type: 'success',
              message: '成功!'
            })
            this.fetchData()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
      }

    },
    setStateTxt(index) {
      console.log(index)
      let str = ''
      switch (index) {
        case 'applying':
          str = '申请中'
          break
        case 'approved':
          str = '审核通过'
          break
        case 'reject':
          str = '审核驳回'
          break
      }
      return str
    },
    fetchData() {
      this.listLoading = true
      if(this.queryParams.startTime && this.queryParams.endTime) {
        this.getStatisticsByStatus()
      }
      withdrawalList(this.queryParams).then(response => {
        response.data.records.map(item => {
          item.type = item.address.indexOf('支付宝') == -1 ? item.address.indexOf('银行') == -1 ? 'usdt' : '银行卡' : '支付宝'
          item.color = item.hasInvest ? '#606266' : '#f00'
        })
        this.list = response.data.records
        this.listLoading = false
        this.total = response.data.total
      })
    },
    handleShowInfo(e) {
      this.$refs.showInfo.show(e)
    },

    onSubmit() {
      this.queryParams.page = 1
      this.fetchData()
    },
    reset() {
      this.queryParams = {
        'hash': '',
        'orderNo': '',
        'pageNum': 1,
        'pageSize': 10,
        'status': '',
        'type': '',
        'userId': '',
        type: ""
      }
      this.fetchData()
    },

    handleEdit(e) {
      this.$refs.showInfo.show(e)
    },
    handleDel(e) {
      this.$confirm('此操作将取消订单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        transactionCancel(e).then(res => {
          this.fetchData()
          this.$message({
            type: 'success',
            message: '成功!'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    }
  }
}
</script>
